<template>
  <div class="login">
    <div class="bgp">
      <div class="login_container">
        <h1>IT课程管理系统</h1>
        <el-form class="login_form" :model="userInfo" :rules="rules" @keyup.enter="onlogin" ref="ref_form">
          <el-form-item prop="username">
            <el-input v-model.trim="userInfo.username" placeholder="请输入用户名">
              <template #prepend>
                <el-icon>
                  <Avatar />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model.trim="userInfo.password" placeholder="请输入密码" show-password>
              <template #prepend>
                <el-icon>
                  <Key />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="login_submit" @click="onlogin">
              登录
            </el-button>
            <div class="login_register" @click="toGo">
              前往注册
            </div>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import router from "../router/index";
import { getLogin } from '../api/index'
/**
 * 初始的ref
 */
const ref_form = ref(null);

/**
 * 表单的数据声明
 */
const userInfo = reactive({
  username: '',
  password: ''
});

/**
 * 表单数据校验
 */
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
  ]
}

/**
 * 登录的方法
 */
const onlogin = () => {
  ref_form.value.validate((val) => {
    console.log("表单验证通过", val)
    if (val) {
      console.log("存在数据",val)
      getLoginData();
    } else {
      ElMessage.error('登录失败了');
    }
  })
}

/**
 * 登录的接口
 */
const getLoginData = async () => {
  try {
    const res = await getLogin({
      username: userInfo.username,
      password: userInfo.password,
    });
    console.log("后端返回的完整数据:", res);

    if (!res) {
      ElMessage.error('登录失败：服务器未返回数据');
      return;
    }

    if (res.code === 200 && res.token) {
      localStorage.setItem('token', res.token);
      ElMessage({
        message: '登录成功',
        type: 'success',
      });
      router.push('/home');
    } else {
      ElMessage.error(res.message || '登录失败：未返回有效的 token');
    }
  } catch (error) {
    console.error("登录接口异常:", error);
    ElMessage.error(error.message || '登录失败，请稍后再试');
  }
};

/**
 * 跳转去注册页面
 */
const toGo = () => {
  router.push('/register')
}
</script>

<style lang='less' scoped>
@-webkit-keyframes fadenum {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

.login {
  height: 100%;
}

.bgp {
  height: 100%;
  background-image: url("../assets/bj.jpg") !important;
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 50%;
}

.el-icon {
  height: 30px !important;
}

.login_container {
  animation: fadenum 1s ease;
  position: absolute;
  z-index: 1;
  width: 400px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  transition: all 1s;
  min-height: 273px;
  text-align: center;
  background-color: #fff;
  border-radius: 10px;
  padding: 20px;

  h1 {
    font-size: 24px;
    transition: all 1s;
    font-weight: bold;
    margin-bottom: 36px;
  }

  .el-card {
    border-radius: 20px;
  }

  .login_form {
    .login_submit {
      width: 100%;
      height: 50px;
      border-radius: 20px;
      margin-bottom: 10px;
    }

    .login_register {
      width: 6.25rem;
      font-size: 0.875rem;
      margin: 0 auto;
    }

    :deep(.el-input-group__prepend) {
      padding: 0 10px;
    }
  }
}
</style>
